using Godot;
using System;

namespace CurrentGame.GUI;


public partial class InteractionTip : Control
{
	[Signal]
	public delegate void InteractionTipTriggerEventHandler();

	[Export]
	public string DisplayText
	{
		get => _displayText;
		set
		{
			if (_displayText != value)
			{
				_displayText = value;
				if (_textLabel != null)
				{
					_textLabel.Text = value;
				}
			}
		}
	}
	private string _displayText = "";

	[Export]
	public float FadeSpeed { get; set; } = 3.0f;

	// Child reference
	private Label _textLabel;
	private bool _enabled = false;
	private float _currentAlpha = 0.0f, _targetAlpha = 0.0f;

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		_textLabel = GetNode<Label>("./Reminder/MarginContainer/Text");
		_textLabel.Text = _displayText;
	}

    public override void _PhysicsProcess(double delta)
    {
        if (_enabled && Mathf.Abs(_targetAlpha - _currentAlpha) > 0.01f)
		{
			_currentAlpha = Mathf.MoveToward(_currentAlpha, _targetAlpha, FadeSpeed * (float)delta);
            Modulate = new Color(1.0f, 1.0f, 1.0f, _currentAlpha);
        }
		else
		{
			_currentAlpha = _targetAlpha;
			Modulate = new Color(1.0f, 1.0f, 1.0f, _currentAlpha);
			_enabled = false;
		}
    }

    public override void _GuiInput(InputEvent @event)
    {
        if (Input.IsActionJustPressed("player_interact"))
		{
			EmitSignal(SignalName.InteractionTipTrigger);
			AcceptEvent();
		}
    }

	// Export interfaces
	public void ShowTip()
	{
		_targetAlpha = 1.0f;
		_enabled = true;
		CallDeferred(MethodName.GrabFocus);
	}

	public void HideTip()
	{
		_targetAlpha = 0.0f;
		_enabled = true;
		ReleaseFocus();
	}

	public void ReGrabFocus()
	{
		// The tip is visible
		if (_targetAlpha > 0.0f) CallDeferred(MethodName.GrabFocus);
    }
}
